package com.tsd.jxc.sale.service.impl;

import com.tsd.base.service.BaseCodeRuleService;
import com.tsd.common.vo.BatchDeleteLogicVo;
import com.tsd.core.constants.Constants;
import com.tsd.core.service.GetDuplicatedObj;
import com.tsd.core.thread.ThreadPoolTaskUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.config.JxcCodeRuleConstants;
import com.tsd.jxc.goods.entity.JxcGoodsPrice;
import com.tsd.jxc.goods.entity.JxcGoodsPriceExt;
import com.tsd.jxc.goods.service.JxcGoodsPriceService;
import com.tsd.jxc.sale.dao.JxcSaleQuotationDetailMapper;
import com.tsd.jxc.sale.dao.JxcSaleQuotationMapper;
import com.tsd.jxc.sale.entity.*;
import com.tsd.jxc.sale.service.JxcSaleOrderService;
import com.tsd.jxc.sale.service.JxcSaleQuotationDetailService;
import com.tsd.jxc.sale.service.JxcSaleQuotationService;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：JxcSaleQuotation 服务实现层
 *
 * @author Hillpool
 * @date 2022/12/12 11:26:43
 */
@Service
public class JxcSaleQuotationServiceImpl extends BaseServiceImpl implements JxcSaleQuotationService, GetDuplicatedObj {

    @Resource
    private JxcSaleQuotationMapper jxcSaleQuotationMapper;
    @Resource
    private JxcSaleQuotationDetailMapper jxcSaleQuotationDetailMapper;
    @Resource
    private BaseCodeRuleService baseCodeRuleService;
    @Resource
    private JxcSaleQuotationDetailService jxcSaleQuotationDetailService;
    @Resource
    private JxcSaleOrderService jxcSaleOrderService;
    @Resource
    private JxcGoodsPriceService jxcGoodsPriceService;

    @Override
    public JxcSaleQuotation getJxcSaleQuotationById(Long id) throws Exception {
        return jxcSaleQuotationMapper.selectByPrimaryKey(id);
    }

    @Override
    public JxcSaleQuotationExt queryBySid(String sid) throws Exception {
        JxcSaleQuotationExt quotationExt = jxcSaleQuotationMapper.selectBySid(sid);
        if (quotationExt != null) {
            List<JxcSaleQuotationDetailExt> detailExtList = jxcSaleQuotationDetailService.queryValidByQuotationList(Collections.singletonList(quotationExt.getSid()));
            quotationExt.setDetail_list(detailExtList);
        }
        return quotationExt;
    }

    @Override
    public void deleteJxcSaleQuotations(List<String> list, SysUser opUser) throws Exception {
        if (HlpUtils.isEmptyList(list)) {
            return;
        }

        BatchDeleteLogicVo logicVo = new BatchDeleteLogicVo(opUser);
        logicVo.setSidList(list);
        jxcSaleQuotationMapper.deleteLogicBySidList(logicVo);

        jxcSaleQuotationDetailMapper.deleteLogicByQuotationList(logicVo);
    }

    @Override
    public boolean isDuplicated(Object obj, String code) {
        if (obj == null) {
            return false;
        }
        JxcSaleQuotationExt orderExt = (JxcSaleQuotationExt) obj;
        orderExt.setCode(code);
        return jxcSaleQuotationMapper.selectDuplicatedCode(orderExt) != null;
    }

    @Override
    public void saveJxcSaleQuotation(JxcSaleQuotationExt record, SysUserExt opUser) throws Exception {
        if (HlpUtils.isEmpty(record.getId())) {
            record.setSys_group_sid(opUser.getGroup_sid());
            record.setSalesman_sid(opUser.getGroup_person_sid());
            super.checkEmpty(record.getClient_sid(), "请提供参数：client_sid");
            if (!HlpUtils.isEmpty(record.getCode())) {
                //如果是手动设置了编号，则检查是否有相同的，有的话，置空后重新生成
                JxcSaleQuotationExt same = jxcSaleQuotationMapper.selectDuplicatedCode(record);
                if (same != null) {
                    record.setCode(null);
                }
            }
            String genCode = baseCodeRuleService.genCode(record.getClient_sid(), JxcCodeRuleConstants.TYPE_JXC_SALE_QUOTATION, JxcCodeRuleConstants.TYPE_NAME_JXC_SALE_QUOTATION, opUser, record.getCode(), record, this);
            record.setCode(genCode);
            if (HlpUtils.isEmpty(record.getFree_shipping())) {
                record.setFree_shipping(0);
            }
            record.setAudit_state(Constants.VALUE_NO);
            record.setState(Constants.VALUE_YES);
            super.autoInjectBaseData(record, opUser, this.TYPE_CREATE, new Date(), record.getQuotation_date());
            jxcSaleQuotationMapper.insertSelective(record);
        } else {
            JxcSaleQuotationExt same = jxcSaleQuotationMapper.selectDuplicatedCode(record);
            if (same != null) {
                throw new HlpException("已存在相同编号的报价单");
            }
            super.autoInjectBaseData(record, opUser, this.TYPE_UPDATE);
            jxcSaleQuotationMapper.updateByPrimaryKeySelective(record);
        }
        jxcSaleQuotationDetailService.saveJxcSaleQuotationDetail(record, opUser);
    }

    @Override
    public List<JxcSaleQuotationExt> findJxcSaleQuotations(Map<String, Object> params, PageBean page) throws Exception {
        if (params.containsKey("with_detail")) {
            return jxcSaleQuotationMapper.selectWithDetailByPage(params, page);
        }
        return jxcSaleQuotationMapper.selectByPage(params, page);
    }

    @Override
    public List<JxcSaleQuotationExt> findJxcSaleQuotations(Map<String, Object> params) throws Exception {
        return jxcSaleQuotationMapper.selectByParams(params);
    }

    @Override
    public void changeJxcSaleQuotationAuditState(List<String> sidList, Integer state, SysUserExt opUser) throws Exception {
        JxcSaleQuotationExt params = new JxcSaleQuotationExt();
        params.setDr(0);
        params.setSid_list(sidList);
        List<JxcSaleQuotationExt> quotationExtList = jxcSaleQuotationMapper.selectByEntity(params);
        if (HlpUtils.isEmptyList(quotationExtList)) {
            throw new HlpException("报价单信息为空");
        }

        List<JxcSaleQuotationExt> filterList = ListUtil.filter(quotationExtList, t -> t.getSale_order() > JxcSaleQuotationExt.GEN_SALE_ORDER_NO);
        if (!HlpUtils.isEmptyList(filterList)) {
            List<String> codeList = ListUtil.map(filterList, JxcSaleQuotationExt::getCode);
            String error = "报价单：" + StringUtils.join(codeList, "、") + " 已生成销售订单，无法";
            error += (state == 1 ? "审核" : "反审");
            throw new HlpException(error);
        }

        filterList = ListUtil.filter(quotationExtList, t -> Constants.VALUE_YES == t.getAudit_state());
        if (state != 1) {
            filterList = ListUtil.filter(quotationExtList, t -> Constants.VALUE_NO == t.getAudit_state());
        }
        if (!HlpUtils.isEmptyList(filterList)) {
            List<String> codeList = ListUtil.map(filterList, JxcSaleQuotationExt::getCode);
            String error = "报价单：" + StringUtils.join(codeList, "、") + " ";
            error += (state == 1 ? "已审核" : "未审核，无法反审");
            throw new HlpException(error);
        }

        List<JxcSaleQuotationExt> updateList = new ArrayList<>();
        for (JxcSaleQuotationExt quotationExt : quotationExtList) {
            if (state == 1) {
                quotationExt.setAudit_state(Constants.VALUE_YES);
                quotationExt.setAuditor_sid(opUser.getSid());
                quotationExt.setAuditor_name(opUser.getName());
                quotationExt.setAudit_date(new Date());
            } else if (state == -1) {
                quotationExt.setAudit_state(Constants.VALUE_NO);
                quotationExt.setAuditor_sid(null);
                quotationExt.setAuditor_name(null);
                quotationExt.setAudit_date(null);
            }
            updateList.add(quotationExt);
        }
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList4Split(updateList, false, itemList -> jxcSaleQuotationMapper.updateList(itemList));
        }
    }

    @Override
    public void genJxcSaleQuotation2SaleOrder(List<String> sidList, SysUserExt opUser) throws Exception {
        JxcSaleQuotationExt params = new JxcSaleQuotationExt();
        params.setDr(0);
        params.setSid_list(sidList);
        List<JxcSaleQuotationExt> quotationExtList = jxcSaleQuotationMapper.selectByEntity(params);
        if (HlpUtils.isEmptyList(quotationExtList)) {
            return;
        }
        List<JxcSaleQuotationExt> filterList = ListUtil.filter(quotationExtList, t -> t.getSale_order() > JxcSaleQuotationExt.GEN_SALE_ORDER_NO);
        if (!HlpUtils.isEmptyList(filterList)) {
            List<String> codeList = ListUtil.map(filterList, JxcSaleQuotationExt::getCode);
            String error = "报价单：" + StringUtils.join(codeList, "、") + " 已生成销售订单";
            throw new HlpException(error);
        }
        List<JxcSaleQuotationExt> updateList = new ArrayList<>();
        List<String> quotationList = ListUtil.map(quotationExtList, JxcSaleQuotationExt::getSid);
        List<JxcSaleQuotationDetailExt> detailExtList = jxcSaleQuotationDetailService.queryValidByQuotationList(quotationList);
        List<String> productList = null;
        for (JxcSaleQuotationExt quotationExt : quotationExtList) {
            List<JxcSaleQuotationDetailExt> filters = ListUtil.filter(detailExtList, t -> quotationExt.getSid().equals(t.getQuotation_sid()));
            if (HlpUtils.isEmptyList(filters)) {
                continue;
            }
            quotationExt.setDetail_list(filters);
            JxcSaleOrderExt orderExt = quotationExt.genSaleOrder();
            List<JxcSaleOrderDetailExt> orderDetailExtList = orderExt.getDetail_list();
            orderExt.setDetail_list(orderDetailExtList);
            orderExt.setSalesman_sid(opUser.getGroup_person_sid());
            jxcSaleOrderService.saveJxcSaleOrder(orderExt, opUser);

            quotationExt.setSale_order(JxcSaleQuotationExt.GEN_SALE_ORDER_ALL);
            super.autoInjectBaseData(quotationExt, opUser, this.TYPE_UPDATE);
            updateList.add(quotationExt);
        }
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList4Split(updateList, false, itemList -> jxcSaleQuotationMapper.updateList(itemList));
        }
    }

    @Override
    public List<JxcSaleQuotationExt> queryJxcSaleQuotationData4Print(List<String> sidList) throws Exception {
        List<JxcSaleQuotationExt> list = ThreadPoolTaskUtil.queryInList4Split(sidList, itemList -> {
            JxcSaleQuotationExt params = new JxcSaleQuotationExt();
            params.setDr(0);
            params.setSid_list(itemList);
            return jxcSaleQuotationMapper.selectByEntity(params);
        });
        if (!HlpUtils.isEmptyList(list)) {
            List<String> orderList = ListUtil.map(list, JxcSaleQuotationExt::getSid);
            List<JxcSaleQuotationDetailExt> detailExtList = jxcSaleQuotationDetailService.queryValidByQuotationList(orderList);
            for (JxcSaleQuotationExt quotationExt : list) {
                List<JxcSaleQuotationDetailExt> filterList = ListUtil.filter(detailExtList, t -> t.getQuotation_sid().equals(quotationExt.getSid()));
                quotationExt.setDetail_list(filterList);
            }
        }
        return list;
    }
}
